package com.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class StudentDAO {
    private Connection connection; // 数据库连接对象

    // 构造函数，接收数据库连接
    public StudentDAO(Connection connection) {
        this.connection = connection;
    }

    // 查询学生信息
    public void queryStudent() throws SQLException {
        String sql = "SELECT * FROM student"; // SQL查询语句，只获取一条记录
        Statement statement = connection.createStatement(); // 创建SQL语句对象
        ResultSet resultSet = statement.executeQuery(sql); // 执行查询并获取结果集

        // 检查结果集是否有数据，并输出第一行的内容
        while (resultSet.next()) {
            System.out.println("id=" + resultSet.getObject("s_id")); // 输出学生ID
            System.out.println("name=" + resultSet.getObject("s_name")); // 输出学生姓名
            System.out.println("age1=" + resultSet.getObject("s_birth")); // 输出学生出生日期
            System.out.println("birthday=" + resultSet.getObject("s_sex")); // 输出学生性别
        }

        resultSet.close(); // 关闭结果集
        statement.close(); // 关闭SQL语句对象
    }

    // 新增学生信息
    public void addStudent(int id, String name, String birth, String sex) throws SQLException {
        String sql = "INSERT INTO student (s_id, s_name, s_birth, s_sex) VALUES (" + id + ", '" + name + "', '" + birth + "', '" + sex + "')";
        Statement statement = connection.createStatement(); // 创建SQL语句对象
        statement.executeUpdate(sql); // 执行插入操作
        statement.close(); // 关闭SQL语句对象
    }

    // 修改学生信息
    public void updateStudent(int id, String name, String birth, String sex) throws SQLException {
        String sql = "UPDATE student SET s_name='" + name + "', s_birth='" + birth + "', s_sex='" + sex + "' WHERE s_id=" + id;
        Statement statement = connection.createStatement(); // 创建SQL语句对象
        statement.executeUpdate(sql); // 执行更新操作
        statement.close(); // 关闭SQL语句对象
    }

    // 删除学生信息
    public void deleteStudent(int id) throws SQLException {
        String sql = "DELETE FROM student WHERE s_id=" + id;
        Statement statement = connection.createStatement(); // 创建SQL语句对象
        statement.executeUpdate(sql); // 执行删除操作
        statement.close(); // 关闭SQL语句对象
    }
}

